<?php
class CControl 
{
    public $view;
    public $uid,$userInfo;
    public $u_role;
    public $u_phone;
    public $token;
    function __construct($val = 0)
    {
        session_start();
        error_reporting(E_ALL);
        ini_set('display_errors',false);
        ini_set('log_errors',1);
        ini_set('error_log',ROOT."/log/err_".date('Ymd').'.txt');
        $this->uid = 0;
        $userInfo = array();
        if($val != 2)
        {
            ///当是2的时候，不需要获取用户信息
            $userInfo = $this->gettoken();
        }
        if($userInfo)
        {
            $this->userInfo = $userInfo;
            $this->uid = (int)$userInfo['id'];
        }
        if($val==1)
        {
            if(empty($this->uid))
            {
                $backarr = ['status'=>'fail','msg'=>'请您先登陆'];
                echo json_encode($backarr,256);
                exit();
            }
        }
        $param = json_decode(URIBASE,true);
        $this->view['paramArr'] = $param;
        $this->view['domain'] = getconfig('domain');
        if($val != 999)
        {
            //当是999的时候不需要记录行为 
           //$this->recordlog();
        }
    }
    public function gettoken()
    {
        $fields_user = $this->_getPost('user_fields');
        $arr = array();
        $token = $this->_getParam('token');
        if(empty($token))
        {
            $token = $this->_getPost('token');
        } 
        $this->token = $token;
        if(!empty($token))
        {
            $_fields = 'id,group_id,money,phone,integral,xhn_coupon_num,leixing,dengji,headimg,name,isforbidden,code3,taobao_id,auth,daili,cash_money,func_amount,is_goback_zc';
            if(!empty($fields_user))
            {
                $_fields .= ",".$fields_user;
            }
            $sql = "select {$_fields} from web_user where token='$token' limit 1";
            $arr = DBData::select($sql);
            if($arr)
            {
                $arr['money'] = ConstModel::baoliufloat($arr['money']);
                $arr['integral'] = ConstModel::baoliufloat($arr['integral']);
            }
        }
        return $arr;
    }
    public function pdrole($role)
    {
        $urole = $this->u_role;
        if($role != $urole)
        {
            $this->alert("权限正确", "/login");
        }
    }
    public function setView($name,$value)
    {
        $this->view[$name] = $value;
    }
    public function getView($name)
    {
        $value = '';
        if(isset($this->view[$name]))
        {
            $value = $this->view[$name];
        }
        return $value;
    }
    public function recordlog()
    {
        /*
        $this->view['paramArr'] = json_decode(URIBASE,true);	
        //记录接口调用日志
        $filename = ROOT."/log/".date("Ymd")."_port.php";
        $txt=date("Y-m-d H:i:s")."\t[uid:".$this->uid."]\t".$_SERVER["REQUEST_URI"]."\t".json_encode($_POST).";\r\n";
        
        if (!file_exists($filename)) { //检查文件是否存在
                $txt="<?php exit; ?>\r\n".$txt;
        }
        file_put_contents($filename,$txt,FILE_APPEND);
        */
        
        if($this->uid > 0)
        {
            
            $data = array(
                'uid'=>$this->uid,
                'add_time'=>time(),
                'control'=>$this->view['paramArr'][1],
                'action'=>$this->view['paramArr'][2],
                'geturl'=>$_SERVER["REQUEST_URI"],
                'postnr'=>json_encode($_POST)
            );
            $tab = 'record_syxhn_cn.user_log_'.date('Ym');
            DBData::intotable($data, $tab);
//            if(!is_dir(ROOT.'/log/'.date("Ymd")))
//            {
//                    mkdir(ROOT.'/log/'.date("Ymd"), 0777, true);
//                    chmod(ROOT.'/log/'.date("Ymd"),0777);
//            }
//            $filename = ROOT.'/log/'.date("Ymd").'/'.$this->uid.'_port.php';
//            file_put_contents($filename,$txt,FILE_APPEND); 
        }
    }
    //记录最后一次的错误
    public function errlog()
    {
        $filename = ERRORLOG."/err_".date("Ymd").".log"; 
        $errarr = error_get_last();
        if($errarr)
        {
            $errlog = json_encode($errarr);
            file_put_contents($filename,date("Y-m-d H:i:s")."\t".$errlog.";\n",FILE_APPEND);
        }
    }
    //$arrary
    public function errother($arrary)
    {
        $errstr = "";
        if(is_array($arrary))
        {
            $errstr = json_encode($arrary,JSON_UNESCAPED_UNICODE);
        }else
        {
            $errstr = $arrary;
        }
        $filename = ERRORLOG."/".date("Ymd")."_err.log"; 
        file_put_contents($filename,date("Y-m-d H:i:s")."\t".$errstr.";\n",FILE_APPEND);
    }
    
    public function mustlogin()
    {
        $uid = $this->uid;
        if(empty($uid))
        {
            $uid = '';
            $this->alert("请您先登录:{$uid}", "/login");
            return '';
        }
    }
    public function transjson($json_str,$act = 'array')
    {
        $tihuan = array(
            '&amp;quot；'=>'"',
            '&amp;#091;'=>'[',
            '&amp;#093;'=>']',
            '&amp;quot;'=>'"',
            '&quot;'=>'"',
            
        );
        $json_str = strtr($json_str, $tihuan);
        if($act == 'array')
        {
            $data = json_decode($json_str, true);
            return $data;
        }else
        {
            return $json_str;
        }
    }
    public function handlejson($json_str)
    {
         $tihuan = array(
            '&amp;#091;'=>'[',
            '&amp;#093;'=>']',
            '&amp;quot;'=>'"',
            
        );
        $json_str = strtr($json_str, $tihuan);
        return $json_str;
    }
    //文本字符串转换为数组 name:value|name:value|name:value
    public function strtransArr($txt_str)
    {
        $Arr = array();
        if(!empty($txt_str))
        {
            $strArr = explode("|",$txt_str);
            foreach($strArr as $value)
            {
                $valueArr = explode(":",$value);
                $Arr[$valueArr[0]] = $valueArr[1];
            }
        }
        return $Arr;
    }
    ////时间比较函数,返回差多少时间
    public function DateDiff($d1,$d2="",$d="d")
    {     
            if(is_string($d1))$d1=strtotime($d1);
            if($d2=="") $d2=date("Y-m-d H:i:s");
            if(is_string($d2))$d2=strtotime($d2); 
            switch($d)
            {
                    case "d":////计算天数
                            $ji=86400;
                            break;
                    case "h":///计算小时
                            $ji=(86400/24);
                            break;
                    case "m":///计算分钟
                            $ji=(86400/24/60);
                            break;
            } 

            return ($d2-$d1)/$ji; 
    }
    public function pageback($_field,$_str,$_url = "")
    {
            $_field=trim($_field);
            if($_field=="")
            {
                echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                if($_url=="")
                {
                die("<script>alert('".$_str."');history.go(-1);</script>") ;
                }
                else
                {
                die("<script>alert('".$_str."');document.location.href='".$_url."';</script>") ;
                }
            }
    }
    public function tourl($url_)
    {
            die("<script>document.location='".$url_."' ;</script>");
    }
    public function toperUrl($str="")
    {
        $perurl = "";
        if(isset($_SERVER['HTTP_REFERER']))
        {
            $perurl=$_SERVER['HTTP_REFERER'];
        }
            
            $perurl = $this->_restr($perurl);
            if(empty($str))
            {
                    $this->tourl($perurl);
            }else
            {
                    $this->pageback("",$str,$perurl);
            }
    }
    public function get($name,$val="")
    { 
        $value = $this->_getParam($name,'str');
        if($val != '' && empty($value))
        {
            $value = $val;
        }
        return $value;
    }
    public function post($name,$val='')
    {
        if($val == 'jsonstr')
        {
            $value = $_POST[$name];
            $data = $this->transjson($value, 'array');
            return $data;
        }else
        {
            $value = $this->_getPost($name,'str');
            if($val != '' && empty($value))
            {
                $value = $val;
            }
            return $value;
        }
    }
    public function _getParam($name,$type='str')
    {
        $val = '';
        if(isset($_GET[$name]))
        {
            $val = $_GET[$name];
            $val = trim($val);
            if(strlen($val) == 0)
            {
                return '';
            } 
            $val = $this->_restr($val);        
        }
        return $val;
    }
    public function _getPost($name,$leixing="str")
    {
        $val = '';
        if(isset($_POST["$name"]))
        {
            $val = $_POST["$name"];
            $val = trim($val);
            if(strlen($val) == 0)
            {
                return '';
            } 
            $val = $this->_restr($val); 
            if($leixing == 'json')
            {
                $val = $this->transjson($val);
            }

            return $val;
        }
        return $val;
    }
    public function posttxt($name,$type='str')
    {
        $val = array();
        if(isset($_POST[$name]))
        {
            $val = $_POST[$name];
            if(!empty($val))
            {
                foreach($val as $k=>$v)
                {
                    switch($type)
                    {
                        case "str":
                            $val[$k] = $this->_restr($v);
                            break;
                    }
                }
                
            }
        }
        return $val;
    }
    //输出纯文本
    public function  _restr($text,$parseBr=false,$nr=false)
    {
        if(!empty($text))
        {
            $str = "document|onclick|onload|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|action|background|codebase|dynsrc|lowsrc"
                    . "|javascript|script|file|'|#";
            $tihuan = array('javascript'=>"");
            $tihuan['document'] = '';
            $tihuan['onclick'] = '';
            $tihuan['onload'] = '';
            $tihuan['unload'] = '';
            $tihuan['iframe'] = '';
            $tihuan['onmouseover'] = '';
            $tihuan['onmouseup'] = '';
            $tihuan['onmouseout'] = '';
            $tihuan['onmousedown'] = '';
            $tihuan['onkeydown'] = '';
            $tihuan['onkeypress'] = '';
            $tihuan['onkeyup'] = '';
            $tihuan['onblur'] = '';
            $tihuan['onchange'] = '';
            $tihuan['onfocus'] = '';
            $tihuan['action'] = '';
            $tihuan['background'] = '';
            $tihuan['codebase'] = '';
            $tihuan['dynsrc'] = '';
            $tihuan['lowsrc'] = '';
            $tihuan['javascript'] = '';
            $tihuan['script'] = '';
            $tihuan['file'] = '';
            $tihuan["'"] = '';
            $tihuan["#"] = '';
            $tihuan['\\'] = '/';
            $tihuan[';'] = '；';
            $tihuan['delete'] = '';
            $tihuan['update'] = '';
            $tihuan['declare'] = '';
            $tihuan['master'] = '';
            $tihuan['exec'] = '';
            $tihuan['script'] = '';
            //腾讯视频问题
            $tihuan['txvideo'] = 'iframe';
            $tihuan['txauto'] = '&tiny=0&auto=0';
            
            
            
            $text = htmlspecialchars_decode($text);
            $text	= $this->safe($text,'text');
            $text	= $this->h($text);
            $text = strtr($text,$tihuan);
            if(!$parseBr&&$nr){
                $text	=	str_ireplace(array("\r","\n","\t","&nbsp;"),'',$text);
                $text	=	htmlspecialchars($text,ENT_QUOTES);
            }elseif(!$nr){
                $text	=	htmlspecialchars($text,ENT_QUOTES);
                }else{
                $text	=	htmlspecialchars($text,ENT_QUOTES);
                $text	=	nl2br($text);
            }
            $text	=	trim($text);
        }
                        
        return $text;
    }
    function safe($text,$type='html',$tagsMethod=true,$attrMethod=true,$xssAuto = 1,$tags=array(),$attr=array(),$tagsBlack=array(),$attrBlack=array())
    {

        //无标签格式
        $text_tags	=	'';

        //只存在字体样式
        $font_tags	=	'<i><b><u><s><em><strong><font><big><small><sup><sub><bdo><h1><h2><h3><h4><h5><h6>';

        //标题摘要基本格式
        $base_tags	=	$font_tags.'<p><br><hr><a><img><map><area><pre><code><q><blockquote><acronym><cite><ins><del><center><strike>';

        //兼容Form格式
        $form_tags	=	$base_tags.'<form><input><textarea><button><select><optgroup><option><label><fieldset><legend>';

        //内容等允许HTML的格式
        $html_tags	=	$base_tags.'<ul><ol><li><dl><dd><dt><table><caption><td><th><tr><thead><tbody><tfoot><col><colgroup><div><span><object><embed>';

        //专题等全HTML格式
        $all_tags	=	$form_tags.$html_tags.'<!DOCTYPE><html><head><title><body><base><basefont><script><noscript><applet><object><param><style><frame><frameset><noframes><iframe>';

        //过滤标签
        $text	=	strip_tags($text, ${$type.'_tags'} );
            //过滤攻击代码
            if($type!='all'){
                //过滤危险的属性，如：过滤on事件lang js
                while(preg_match('/(<[^><]+) (document|onclick|onload|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|action|background|codebase|dynsrc|lowsrc)([^><]*)/i',$text,$mat)){
                    $text	=	str_ireplace($mat[0],$mat[1].$mat[3],$text);
                }
                while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
                    $text	=	str_ireplace($mat[0],$mat[1].$mat[3],$text);
                }
            }
            return $text;
    }
    //输出安全的html
    function h($text, $tags = null)
    {
            $text	=	trim($text);
            $text	=	preg_replace('/<!--?.*-->/','',$text);
            //完全过滤注释
            $text	=	preg_replace('/<!--?.*-->/','',$text);
            //完全过滤动态代码
            $text	=	preg_replace('/<\?|\?'.'>/','',$text);
            //完全过滤js
            $text	=	preg_replace('/<script?.*\/script>/','',$text);

            $text	=	str_replace('[','&#091;',$text);
            $text	=	str_replace(']','&#093;',$text);
                        
            //过滤换行符
            $text	=	preg_replace('/\r?\n/','',$text);
            //br
            $text	=	preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
            $text	=	preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
            //过滤危险的属性，如：过滤on事件lang js
            while(preg_match('/(<[^><]+) (lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
                    $text=str_replace($mat[0],$mat[1],$text);
            }
            while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
                    $text=str_replace($mat[0],$mat[1].$mat[3],$text);
            }
            if(empty($tags)) {
                    $tags = 'table|tbody|td|th|tr|i|b|u|strong|img|p|br|div|span|em|ul|ol|li|dl|dd|dt|a|alt|h[1-9]?';
                    $tags.= '|object|param|embed';	// 音乐和视频
            }
            //允许的HTML标签
            $text	=	preg_replace('/<(\/?(?:'.$tags.'))( [^><\[\]]*)?>/i','[\1\2]',$text);
            //过滤多余html
            $text	=	preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|style|xml)[^><]*>/i','',$text);
            //过滤合法的html标签
            while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
                    $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
            }
            //转换引号
            while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
                    $text = str_replace($mat[0], $mat[1] . '|' . $mat[3] . '|' . $mat[4],$text);
            }
            //过滤错误的单个引号
            // 修改:2011.05.26 kissy编辑器中表情等会包含空引号, 简单的过滤会导致错误
    //	while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
    //		$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
    //	}
            //转换其它所有不合法的 < >
            $text	=	str_replace('<','&lt;',$text);
            $text	=	str_replace('>','&gt;',$text);
            $text   =   str_replace('"','&quot;',$text);
            //$text   =   str_replace('\'','&#039;',$text);
             //反转换
            $text	=	str_replace('[','<',$text);
            $text	=	str_replace(']','>',$text);
                        
            //过滤多余空格
            $text	=	str_replace('  ',' ',$text);
            return $text;
    }
    public function display($url="")
    {
        if(!empty($url))
        {
            if(file_exists(VIEW."/".$url))
            {
                include VIEW."/".$url;
            }
        }else
        {
            $c = $this->view['paramArr'][1];
            $a = $this->view['paramArr'][2];
            $url = $c.'/'.$a.'.php';
            if(file_exists(VIEW.'/'.$url))
            {
                include VIEW."/".$url;
            }
        }	
        
    }
    public function alert($content,$url="")
    {
        $this->view['alert_title'] = $content;
        $this->view['url'] = $url;
        include VIEW."/alert.php";
        return false;
    }
    
    public function repUrl($url)
    {
        if(!empty($url))
        {
            $tihuan = array('|'=>'/','*'=>'?');
            $url = strtr($url, $tihuan);
        }
        return $url;
    }
    public function fanzhuan($str)
    {
        $tihuan = array('&amp;#124;'=>'|','&quot;'=>'"');
        $restr = '';
        if(!empty($str))
        {
            $restr = strtr($str, $tihuan);
        }
        return $restr;
    }
    public function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
    {
        $str=self::delhtml($str);
        if(function_exists("mb_substr"))
                return mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
                return iconv_substr($str,$start,$length,$charset);
        }
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']	  = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']	  = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
        if($suffix) return $slice."…";
        return $slice;
    }
    public function delhtml($str)
    {
        return str_replace(array("\r","\n","\t"), array('','',''), strip_tags($str));
    }
    
    public function _pdcontrol($control,$action)
    {
        $tf = false;
        if($control == $this->view['paramArr'][1] && $action == $this->view['paramArr'][2])
        {
            $tf = true;
        }
        return $tf;
    }
}
?>